package com.speed_run.service;

import com.speed_run.global.LoginType;
import com.speed_run.mapper.AuthMapper;
import com.speed_run.mapper.UserMapper;
import com.speed_run.model.UserAuth;
import com.speed_run.model.UserInfo;
import com.speed_run.service.thirdLogin.IThirdLoginService;
import com.speed_run.service.thirdLogin.PhoneLoginServiceImpl;
import com.speed_run.service.thirdLogin.WeiboLoginServiceImpl;
import com.speed_run.service.thirdLogin.WeichatLoginServiceImpl;
import com.speed_run.utils.JwtUtils;
import com.speed_run.utils.ResponseEntity;
import com.speed_run.vo.NameAndPassWord;
import com.speed_run.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private AuthMapper authMapper;

	@Value("${config.host}")
	private String host;
	/**
	 * 更新信息
	 * @param vo
	 */
	public void save(UserVo vo){
		//userInfoDao.save(vo.userInfo());
	}
	/**
	 * 登录认证
	 * @param token
	 * @return
	 */
	public ResponseEntity auth(NameAndPassWord token){
		//Subject subject = SecurityUtils.getSubject();
		//getLoginService(LoginType.valueOf(token.getLoginType())).login(subject,token.getNP());
		//登录成功返回用户token
		//UserAuth auth = (UserAuth) subject.getPrincipal();
		UserAuth auth = authMapper.login(token.getUserName(),token.getPassWord());
		if(auth == null){
		 return	ResponseEntity.fail("用户名或密码错误");
		}
		UserInfo info = userMapper.findUser(auth.getUserId());
		/*UserInfoDTO dto = new UserInfoDTO();
		dto.setAvator(info.getAvator());
		dto.setNickName(info.getNickName());*/
		Map<String, String> map = new HashMap<>();
		map.put("nickName",info.getNickName());
		map.put("avator", StringUtils.isEmpty(info.getAvator())?"":host+info.getAvator());
		map.put("token",JwtUtils.generateToken(info.getUserId()));
		map.put("userId",info.getUserId());
		return  ResponseEntity.ok("登录成功",map);
	}

	private IThirdLoginService getLoginService(LoginType type){
		switch (type){
			case TEL:
				return new PhoneLoginServiceImpl();
			case WECHAT:
				return new WeichatLoginServiceImpl();
			case QQ:
				return new WeiboLoginServiceImpl();
			default:
				return null;
		}
	}
}
